﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Jinshiyu.Models;

namespace Jinshiyu.Controllers
{
    public class CMemberController : Controller
    {
        private JinshiyuEntities db = new JinshiyuEntities();


        public ActionResult LogOn()
        {
            return View();
        }


        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    var cMember = new C会员();
                    try
                    {
                        db.CMembers.Single(m => m.账户 == model.UserName);
                    }
                    catch (Exception e)
                    {
                        Membership.DeleteUser(model.UserName);

                        return RedirectToAction("LogOff");
                    }

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码不正确");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }


        public ActionResult GetValidateCode()
        {
            return View();
        }


        [HttpPost]
        public ActionResult GetValidateCode(GetValidateCodeModel model)
        {
            if (ModelState.IsValid)
            {
                C会员 cMember;
                if (db.CMembers.Any<C会员>(c => c.账户 == model.UserName))//先查询C会员表中是否存在该手机号
                {
                    //重发一个验证码，并更新注册时间
                    cMember = db.CMembers.First<C会员>(c => c.账户 == model.UserName);

                    if (cMember.密码 != null)//密码不为null，说明已经用户名已经注册成功
                    {
                        return RedirectToAction("GetValidateCodeFail");
                    }


                }
                else
                {
                    //向C会员表插入一条空的新记录，生成一个验证码发送到手机上
                    cMember = new C会员();
                    cMember.账户 = model.UserName;
                    cMember.手机 = model.UserName;
                    db.CMembers.Add(cMember);
                }


                cMember.注册时间 = DateTime.Now;
                db.SaveChanges();

                TempData["username"] = model.UserName;
            }
            else
            {
                ModelState.AddModelError("", "请检查您输入的手机号是否为11位数字");
            }
            return RedirectToAction("Register", "CMember", new { username = model.UserName });
        }


        public ActionResult Register(string username)
        {
            var regModel = new RegisterModel();
            regModel.UserName = username;

            return View(regModel);
        }


        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            C会员 cMember;
            try
            {
                cMember = db.CMembers.First(c => c.账户 == model.UserName && c.验证码 == model.ValidateCode);
                if (ModelState.IsValid)
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(model.UserName, model.Password, null, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        //更新C会员内当前用户记录

                        cMember.密码 = model.Password;

                        db.SaveChanges();

                        FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                        return RedirectToAction("RegisterSuccess");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }


        [Authorize]
        public ActionResult RegisterSuccess()
        {
            return View();
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }


        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    System.Web.Security.MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("","");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        public ActionResult GetValidateCodeFail()
        {
            return View();
        }


        [Authorize]
        public ActionResult UpdateCMemberInfo()
        {
            var updater = new CMemberViewModel();
            try
            {
                var cMember = db.CMembers.Single(c => c.账户 == User.Identity.Name);
                updater.账户 = cMember.账户;
                updater.姓名 = cMember.姓名;
                updater.性别 = cMember.性别;
                updater.手机 = cMember.手机;
                updater.电话 = cMember.电话;
                updater.Email = cMember.电子邮件;
                updater.联系地址 = cMember.联系地址;
                updater.城市 = cMember.城市;
                updater.城区 = cMember.城区;
                updater.小区 = cMember.小区;
            }
            catch (Exception e)
            {
                throw e;
            }

            return View(updater);
        }


        [HttpPost]
        [Authorize]
        public ActionResult UpdateCMemberInfo(CMemberViewModel model)
        {
            var cMember = db.CMembers.First<C会员>(c => c.账户 == User.Identity.Name);

            cMember.姓名 = model.姓名;
            cMember.性别 = model.性别;
            cMember.手机 = model.手机;
            cMember.电话 = model.电话;
            cMember.电子邮件 = model.Email;
            cMember.联系地址 = model.联系地址;
            cMember.城市 = model.城市;
            cMember.城区 = model.城区;
            cMember.小区 = model.小区;

            db.SaveChanges();

            return RedirectToAction("UpdateCMemberInfoSuccess");
        }

        [Authorize]
        public ActionResult UpdateCMemberInfoSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
